package parser

import (
	"learngo/crawler/engine"
	"learngo/crawler/model"
	"regexp"
)

var basicsRe = regexp.MustCompile(`<div class="m-btn purple"[^<]*>([^<]+)</div>`)
var extendRe = regexp.MustCompile(`<div class="m-btn pink"[^<]*>([^<]+)</div>`)
var wantRe = regexp.MustCompile(`<div class="m-btn"[^<]*>([^<]+)</div>`)
var genderRe = regexp.MustCompile(`([他她])的动态`)
var idUrlRe = regexp.MustCompile(`https://album.zhenai.com/u/([\d]+)`)

func parseProfile(contents []byte, url string, name string) engine.ParseResult {

	profile := model.Profile{}
	profile.Name = name
	gender := genderRe.FindSubmatch(contents)
	if gender != nil {
		if string(gender[1]) == "他" {
			profile.Gender = "男"
		}
		if string(gender[1]) == "她" {
			profile.Gender = "女"
		}
	}
	matches := basicsRe.FindAllSubmatch(contents, -1)
	for _, m := range matches {
		profile.BasicMessage = append(profile.BasicMessage, string(m[1]))
	}
	exMatches := extendRe.FindAllSubmatch(contents, -1)
	for _, m := range exMatches {
		profile.ExpendMessage = append(profile.ExpendMessage, string(m[1]))
	}
	waMatches := wantRe.FindAllSubmatch(contents, -1)
	for _, m := range waMatches {
		profile.ExpectMessage = append(profile.ExpectMessage, string(m[1]))
	}
	//result.Items = append(result.Items, "User " + name)
	result := engine.ParseResult{
		Items: []engine.Item{
			{
				Url:     url,
				Type:    "zhenai",
				Id:      extractString([]byte(url), idUrlRe),
				Payload: profile,
			},
		},
	}
	return result
}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)
	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}

type ProfileParser struct {
	userName string
}

func (p *ProfileParser) Parse(contents []byte, url string) engine.ParseResult {
	return parseProfile(contents, url, p.userName)
}

func (p *ProfileParser) Serialize() (name string, args interface{}) {
	return "ProfileParse", p.userName
}

func NewProfileParser(name string) *ProfileParser {
	return &ProfileParser{
		userName: name,
	}
}
